namespace SsisLdapSource.InstantiationTime
{
    using System;
    using System.ComponentModel;
    using System.Globalization;

    public class CommaDelimitedToStringArrayTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                var v = Convert.ToString(value, culture).Split(new[] { ',' });
                return v;
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                var s = string.Empty;
                foreach (var component in (string[])value)
                {
                    s = s + component + ",";
                }

                if (s.EndsWith(",", StringComparison.Ordinal))
                {
                    s = s.Substring(0, s.Length - 1);
                }

                return s;
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}

